import { getRepository } from 'typeorm';
import { User } from '../entity/User';
async function role(req, res, next) {
  // console.log('req', req.path);
  if (req.url.indexOf('/api') === -1) {
    await next();
    return;
  }

  // 白名单：有些操作我们是不需要鉴权的
  const whitelist = ['/api/users/login', '/api/users/register', '/api/upload'];
  if (!whitelist.includes(req.path)) {
    if (req.path.indexOf('role') != -1 || req.path.indexOf('users') != -1) {
      // console.log('非白名单请求');
      // console.log('headers', req.headers.token);
      if (req.headers.token) {
        let username = req.headers.token.split('*')[0];
        let token = req.headers.token.split('*')[1];
        if (username == 'admin@admin.com') {
          await next();
          return;
        }
        let userRepository = getRepository(User);
        let user = await userRepository.findOne({
          relations: ['role'],
          where: {
            token: token,
          },
        });
        if (user.role && user.role.admin === 1) {
          await next();
          return;
        } else {
          res.send({
            message: '您没有访问权限！',
            code: 403,
            success: false,
          });
          return;
        }
      } else {
        res.send({
          message: '您没有访问权限！',
          code: 403,
          success: false,
        });
        return;
      }
    } else {
      await next();
      return;
    }
  }
  await next();
}
module.exports = { role };
